//
//  WBRefreshControl.swift
//  BAweibo
//
//  Created by baggio on 2017/8/31.
//  Copyright © 2017年 baggio. All rights reserved.
//

import UIKit

//下拉刷新控件偏移量
private let WBRefreshControlOffset: CGFloat = -50

class WBRefreshControl: UIRefreshControl {

    override init() {
        super.init()
        
        setUpUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        //fatalError("init(coder:) has not been implemented")
        
        super.init(coder: aDecoder)
        
        setUpUI()
    }
    
    private func setUpUI() {
        //隐藏转轮
        tintColor = UIColor.clear
        
        addSubview(refreshView)
        
        refreshView.snp.makeConstraints { (m) in
            m.center.equalTo(self)
            m.size.equalTo(refreshView.bounds.size)
        }
        
        
        DispatchQueue.main.async {
            //self.frame，"frame"不能写错
            self.addObserver(self, forKeyPath: "frame", options: [], context: nil)
        }
    }
    
    //删除 KVO 监听方法
    deinit {
        self.removeObserver(self, forKeyPath: "frame")
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {

        //print(frame.origin.y)
        //frame.origin.y 默认为 0 ，越往下拉，y值越小
        
        if frame.origin.y > 0{
            print("over")
            return
        }
        
        //
        if isRefreshing {
            refreshView.startAnimation()
        }
        
        if frame.origin.y < WBRefreshControlOffset && !refreshView.rotateFlag {
            print("反过来，箭头向上")
            refreshView.rotateFlag = true
        } else if frame.origin.y >= WBRefreshControlOffset && refreshView.rotateFlag {
            print("翻回去，箭头向下")
            refreshView.rotateFlag = false
        }
    }
    
    //
    override func endRefreshing() {
        super.endRefreshing()
        
        refreshView.stopAnimation()
    }
    
    //
    override func beginRefreshing() {
        super.beginRefreshing()
        
        refreshView.startAnimation()
    }
    
    
    //懒加载控件
    private lazy var refreshView = WBRefreshView.refreshView()
}
